<template>
  <div>
    <el-card shadow="always">
      <el-form :inline="true" :model="vo" ref="paraVo" class="demo-form-inline">

        <el-form-item label="账号:" prop="account">
          <el-input v-model="vo.account" placeholder="货物类型名称:"></el-input>
        </el-form-item>

        <el-form-item label="组织">
          <div class="selectTree">
            <el-select v-model="dictDataSelect" placeholder="请选择组织" ref="selectReport">
              <el-option :value="dictDataSelect" :label="dictDataSelect" style="height: auto;">
                <el-tree
                  :data="list"
                  :props="defaultProps"
                  :render-after-expand="true"
                  :expand-on-click-node="false"
                  @node-click="handleNodeClick">
                </el-tree>
              </el-option>
            </el-select>
          </div>
        </el-form-item>

        <el-form-item>
          <el-date-picker
            v-model="dateTime"
            type="datetimerange"
            range-separator="-"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="el">搜索</el-button>
          <el-button @click="resetForm('paraVo')" icon="el-icon-refresh">重置</el-button>
          <el-dropdown>
            <el-button>
              更多菜单<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="insertButton">添加</el-dropdown-item>
              <el-dropdown-item @click.native="deleteButton">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-form-item>
      </el-form>
    </el-card>
    <el-divider></el-divider>
    <el-card class="box-card">
      <el-table
        ref="multipleTable"
        v-loading="loading"
        :data="pageData.records"
        style="width: 100%">

        <el-table-column
          type="selection"
          width="55">
        </el-table-column>

        <el-table-column
          width="100"
          label="头像">
          <template slot-scope="scop">
            <el-avatar :size="40" :src="ossaddr+'/'+scop.row.pdAuthUser.avatar"></el-avatar>
          </template>
        </el-table-column>

        <el-table-column
          width="100"
          prop="pdAuthUser.account"
          label="账号">
        </el-table-column>

        <el-table-column
          width="150"
          prop="pdAuthUser.name"
          label="姓名">
        </el-table-column>

        <el-table-column
          width="100"
          label="性别">
          <template slot-scope="scop">
            <el-tag v-if="scop.row.pdAuthUser.sex == 'M'">男</el-tag>
            <el-tag type="success" v-else-if="scop.row.pdAuthUser.sex == 'W'">女</el-tag>
            <el-tag type="warning" v-else>未知</el-tag>
          </template>
        </el-table-column>

        <el-table-column
          width="200"
          prop="pdAuthUser.email"
          label="邮箱">
        </el-table-column>

        <el-table-column
          width="200"
          prop="pdCoreOrg.name"
          label="组织">
        </el-table-column>

        <el-table-column
          width="150"
          prop="pdCoreStation.name"
          label="岗位">
        </el-table-column>

        <el-table-column
          width="100"
          label="状态">
          <template slot-scope="scop">
            <label style="color: #409EFF" v-if="scop.row.pdAuthUser.status===true">启用</label>
            <label style="color: red" v-if="scop.row.pdAuthUser.status===false">禁用</label>
          </template>
        </el-table-column>

        <el-table-column
          width="200"
          prop="pdAuthUser.createTime"
          label="创建时间">
        </el-table-column>

        <el-table-column
          fixed="right"
          label="操作"
          width="150">
          <template slot-scope="scope">
            <el-button type="text" size="medium" @click="CheckData(scope.row)">查看</el-button>
            <el-button type="text" size="medium" @click="updateButton(scope.row.pdAuthUser,scope.row.pdCoreOrg)">修改
            </el-button>
            <el-button style="color: red" type="text" @click="delUser(scope.row.pdAuthUser.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: center">
        <br>
        <el-pagination
          @size-change="setSize"
          @current-change="setPage"
          :current-page="pageData.current"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageData.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageData.total">
        </el-pagination>
      </div>
    </el-card>
    <!--  查看对话框  -->
    <el-dialog
      title="查看"
      :visible.sync="dialogVisible"
      :before-close="closeModel"
      width="60%">
      <div style="text-align: center">
        <el-avatar :size="60" :src="ossaddr+'/'+pdAuthUser.avatar"></el-avatar>
      </div>
      <el-divider></el-divider>
      <div style="font-size: 15px;font-family: youyuan;font-weight: bold">
        <el-row>
          <el-col :span="12">
            <i class="el-icon-user"></i>
            <el-divider direction="vertical"></el-divider>
            用户：{{ pdAuthUser.account }}
          </el-col>
          <el-col :span="12">
            <i class="el-icon-suitcase"></i>
            <el-divider direction="vertical"></el-divider>
            姓名：{{ pdAuthUser.name }}
          </el-col>
        </el-row>
        <br>
        <el-row>
          <el-col :span="12">
            <i class="el-icon-user"></i>
            <el-divider direction="vertical"></el-divider>
            邮箱：{{ pdAuthUser.email }}
          </el-col>
          <el-col :span="12">
            <i class="el-icon-suitcase"></i>
            <el-divider direction="vertical"></el-divider>
            电话：{{ pdAuthUser.name }}
          </el-col>
        </el-row>
        <br>
        <el-row>
          <el-col :span="12">
            <i class="el-icon-user"></i>
            <el-divider direction="vertical"></el-divider>
            组织：{{ pdCoreOrg.name }}
          </el-col>
          <el-col :span="12">
            <i class="el-icon-suitcase"></i>
            <el-divider direction="vertical"></el-divider>
            岗位：{{ pdCoreStation.name }}
          </el-col>
        </el-row>
        <br>
        <el-row>
          <el-col :span="12">
            <i class="el-icon-user"></i>
            <el-divider direction="vertical"></el-divider>
            性别：
            <label v-if="pdAuthUser.sex == 'M'">男</label>
            <label type="success" v-else-if="pdAuthUser.sex == 'W'">女</label>
            <label type="warning" v-else>未知</label>
          </el-col>
          <el-col :span="12">
            <i class="el-icon-suitcase"></i>
            <el-divider direction="vertical"></el-divider>
            状态：
            <label v-if="pdAuthUser.status===true">启用</label>
            <label v-if="pdAuthUser.status===false">禁用</label>
          </el-col>
        </el-row>
        <br>
        <el-row>
          <el-col :span="12">
            <i class="el-icon-user"></i>
            <el-divider direction="vertical"></el-divider>
            创建时间：{{ pdAuthUser.createTime }}
          </el-col>
          <el-col :span="12">
            <i class="el-icon-suitcase"></i>
            <el-divider direction="vertical"></el-divider>
            修改时间：{{ pdAuthUser.updateTime }}
          </el-col>
        </el-row>
        <br>
        <el-row>
          <el-col :span="12">
            <i class="el-icon-user"></i>
            <el-divider direction="vertical"></el-divider>
            最后登录时间：{{ pdAuthUser.lastLoginTime }}
          </el-col>
          <el-col :span="12">
            <i class="el-icon-suitcase"></i>
            <el-divider direction="vertical"></el-divider>
            密码过期时间：{{ pdAuthUser.passwordExpireTime }}
          </el-col>
        </el-row>
        <br>
        <el-row>
          <el-col :span="12">
            <i class="el-icon-user"></i>
            <el-divider direction="vertical"></el-divider>
            最后一次输错密码的时间：{{ pdAuthUser.passwordErrorLastTime }}
          </el-col>
          <el-col :span="12">
            <i class="el-icon-suitcase"></i>
            <el-divider direction="vertical"></el-divider>
            密码错误次数：{{ pdAuthUser.passwordErrorNum }}
          </el-col>
        </el-row>
        <br>
        <el-row>
          <el-col :span="24">
            <i class="el-icon-user"></i>
            <el-divider direction="vertical"></el-divider>
            个人描述：{{ pdAuthUser.workDescribe }}
          </el-col>
        </el-row>
      </div>
    </el-dialog>
    <!--  新增修改对话框  -->
    <el-dialog
      :title="insertUpdateText"
      :visible.sync="insertUpdatedialogVisible"
      :before-close="closeModel"
      width="40%">
      <el-form :model="userData" ref="userFrom" label-width="100px">

        <el-form-item label="账号" prop="account" v-if="buttonStatus === 1">
          <el-input v-model="userData.account"></el-input>
        </el-form-item>

        <el-form-item label="账号" prop="account" v-if="buttonStatus === 2">
          <el-input v-model="userData.account" disabled></el-input>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="userData.name"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password" v-if="buttonStatus === 1">
          <el-input show-password v-model="userData.password"></el-input>
        </el-form-item>

        <el-form-item label="照片">
          <el-upload
            class="avatar-uploader"
            action="/OSSFileApi/file/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="userData.avatar" :src="ossaddr+'/'+userData.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="组织">
          <el-select v-model="inupDictDataSelect" placeholder="请选择组织" ref="selectReport">
            <el-option :value="inupDictDataSelect" :label="inupDictDataSelect" style="height: auto;">
              <el-tree
                :data="list"
                :props="defaultProps"
                :render-after-expand="true"
                :expand-on-click-node="false"
                @node-click="inupHandleNodeClick">
              </el-tree>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="岗位" prop="stationId">
          <el-select v-model="userData.stationId" placeholder="请选择岗位" ref="selectReport">
            <el-option
              v-for="selectData in pdCoreOrgSelectData"
              :label="selectData.name"
              :value="selectData.id"
              :key="selectData.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userData.email"></el-input>
        </el-form-item>

        <el-form-item label="电话" prop="mobile">
          <el-input v-model="userData.mobile"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select size="small" v-model="userData.sex" placeholder="请选择性别" ref="selectReport">
            <el-option
              v-for="arrdata in selectData"
              :label="arrdata.value"
              :value="arrdata.key"
              :key="arrdata.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="个人描述" prop="workDescribe">
          <el-input v-model="userData.workDescribe"></el-input>
        </el-form-item>
      </el-form>

      <div style="text-align: center">
        <el-button @click="clearModel">取 消</el-button>
        <el-button type="danger" @click="insertGoods" v-if="buttonStatus===1">确认</el-button>
        <el-button type="danger" @click="updateGoods" v-if="buttonStatus===2">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import userManagementAPI from "../../api/rightsmanagement/usermanagement/userManagement";
import organizationAPI from "../../api/rightsmanagement/organizationmanagement/organization";
import {mapState} from 'vuex'

export default {
  computed: {
    ...mapState(['ossaddr']),
    dateTime: {
      get() {
        if (this.vo.startTime && this.vo.stopTime) {
          return [this.vo.startTime, this.vo.stopTime]
        } else {
          return []
        }
      },
      set(v) {
        this.vo.startTime = v[0]
        this.vo.stopTime = v[1]
      }
    }
  },
  data() {
    return {
      dictDataSelect: null,// 选择后显示的数据
      inupDictDataSelect: null,// 修改添加选择后显示的数据
      list: [], // 树数据
      defaultProps: { // 树规则
        children: 'orgTreeDtoList',
        label: 'name'
      },
      // 日期快捷键
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      loading: false,
      vo: {
        "account": null,
        "orgId": null,
        "startTime": null,
        "stopTime": null,
        "num": "1",
        "size": "5"
      },
      pageData: [],
      dialogVisible: false,
      insertUpdatedialogVisible: false,
      insertUpdateText: null,
      pdAuthUser: {},
      pdCoreOrg: {},
      pdCoreStation: {},
      buttonStatus: -1,
      userData: {
        id: null,
        account: null,
        name: null,
        password: null,
        avatar: null,
        orgId: null,
        stationId: null,
        email: null,
        mobile: null,
        sex: 'N',
        status: 1,
        workDescribe: null
      },
      selectData: [ // 性别状态
        {"key": "M", "value": "男"},
        {"key": "W", "value": "女"},
        {"key": "N", "value": "未知"},
      ],
      pdCoreOrgSelectData: [] // 岗位数据
    }
  },
  methods: {
    // 下拉菜单的节点赋值
    handleNodeClick(node) {
      this.dictDataSelect = node.name;
      this.vo.orgId = node.id;
      this.$refs.selectReport.blur()
    },
    // 修改和添加的下拉赋值
    inupHandleNodeClick(node) {
      this.inupDictDataSelect = node.name;
      this.userData.orgId = node.id;
      this.$refs.selectReport.blur()
      // 根据选中的组织查询岗位
      this.getPdCoreOrgData(node.id)
    },
    // 请求岗位
    getPdCoreOrgData(data) {
      // 根据选择的组织id查询岗位
      userManagementAPI.getPdCoreOrg(data).then(({data}) => {
        this.pdCoreOrgSelectData = data.data
      })

    },
    // 请求用户信息
    el() {
      this.loading = true
      userManagementAPI.sellUserData(this.vo).then(({data}) => {
        this.loading = false
        this.pageData = data.data
      })
    },
    // 拉取组织树的数据
    getSelectOption() {
      organizationAPI.getTreeData(this.vo.name).then(({data}) => {
        this.dg(data.data);
        this.list = data.data;
      })
    },
    // 组织树递归（添加id和name）
    dg(data) {
      if (data != null) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].orgTreeDtoList.length > 0) {
            this.dg(data[i].orgTreeDtoList)
          }
          this.$set(data[i], 'name', data[i].pdCoreOrg.name)
          this.$set(data[i], 'id', data[i].pdCoreOrg.id)
        }
      }
    },
    // 设置页条数
    setSize(num) {
      this.vo.size = num
      this.el()
    },
    // 设置当前页
    setPage(num) {
      this.vo.num = num
      this.el()
    },
    // 重置
    resetForm(formName) {
      this.vo.startTime = null
      this.vo.stopTime = null
      this.dictDataSelect = null;
      this.vo.orgId = null;
      this.$refs[formName].resetFields()
    },
    // 查看功能模态框
    closeModel() {
      this.$confirm('确认关闭？').then(() => {
        this.clearModel()
      })
    },
    // 查看数据
    CheckData(data) {
      this.pdAuthUser = data.pdAuthUser
      this.pdCoreOrg = data.pdCoreOrg
      this.pdCoreStation = data.pdCoreStation
      this.dialogVisible = true
    },
    // 关闭模态框
    clearModel() {
      // 清空树菜单
      this.inupDictDataSelect = null
      // 清空组织
      this.pdCoreOrgSelectData = []
      // 赋值原数据
      this.userData.id = null
      this.userData.account = null
      this.userData.name = null
      this.userData.password = null
      this.userData.avatar = null
      this.userData.orgId = null
      this.userData.stationId = null
      this.userData.email = null
      this.userData.mobile = null
      this.userData.sex = "M"
      this.userData.status = 1
      this.userData.workDescribe = null

      // 设置默认状态
      this.buttonStatus = -1
      // 设置title为空
      this.insertUpdateText = null
      this.dialogVisible = false
      this.insertUpdatedialogVisible = false
    },
    // 删除
    delUser(uid) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userManagementAPI.deleteUserInfo({idList: [uid]}).then(({data}) => {
          if (data.code === 200) {
            this.$message({
              message: data.message,
              type: 'success'
            });
            this.el();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 批量删除
    deleteButton() {
      let array = this.$refs.multipleTable.selection
      if (array.length > 0) {
        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids = [];
          for (let i in array) {
            ids[ids.length] = array[i].pdAuthUser.id
          }
          userManagementAPI.deleteUserInfo({idList: ids}).then(({data}) => {
            if (data.code === 200) {
              this.$message({
                message: data.message,
                type: 'success'
              });
              this.el();
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.$message({
          message: '至少选择一项',
          type: 'warning'
        });
      }
    },
    // 修改按钮
    updateButton(data, data2) {
      this.$store.commit("startAnimation", true);

      // 赋值组织
      this.inupDictDataSelect = data2 == null ? null : data2.name

      // 赋值原数据
      this.userData.id = data.id
      this.userData.account = data.account
      this.userData.name = data.name
      this.userData.avatar = data.avatar
      this.userData.orgId = data.orgId
      this.userData.stationId = data.stationId
      this.userData.email = data.email
      this.userData.mobile = data.mobile
      this.userData.sex = data.sex + ''
      this.userData.status = data.status ? 1 : 0
      this.userData.workDescribe = data.workDescribe

      // 查询当前组织的岗位
      userManagementAPI.getPdCoreOrg(data.orgId).then(({data}) => {
        this.pdCoreOrgSelectData = data.data
        // 开启模态框
        this.buttonStatus = 2
        this.insertUpdateText = '修改'
        this.insertUpdatedialogVisible = true
        this.$store.commit("startAnimation", false);
      })
    },
    // 添加按钮
    insertButton() {
      this.buttonStatus = 1
      this.insertUpdateText = '添加'
      this.insertUpdatedialogVisible = true
    },
    // 上传成功后
    handleAvatarSuccess(res, file) {
      if (res.code === 200) {
        this.$store.commit("startAnimation", false);
        this.userData.avatar = res.data.url
        this.userData.avatar = res.data.url
        this.$message({
          message: res.message,
          type: 'success'
        });
      }
    },
    // 上传之前
    beforeAvatarUpload(file) {
      this.$store.commit("startAnimation", true);
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$store.commit("startAnimation", false);
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$store.commit("startAnimation", false);
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 修改
    updateGoods() {
      console.log(this.userData)
      this.$store.commit("startAnimation", true);
      userManagementAPI.updateUserData(this.userData).then(({data}) => {
        this.$store.commit("startAnimation", false);
        if (data.code === 200) {
          this.$message({
            message: data.message,
            type: 'success'
          });
          this.el();
          this.clearModel();
        }
      })
    },
    // 添加
    insertGoods() {
      console.log(this.userData)
      this.$store.commit("startAnimation", true);
      userManagementAPI.insertUserData(this.userData).then(({data}) => {
        this.$store.commit("startAnimation", false);
        if (data.code === 200) {
          this.$message({
            message: data.message,
            type: 'success'
          });
          this.el();
          this.clearModel();
        }
      })
    }
  },
  // 初始化
  created() {
    this.el()
    this.getSelectOption()
  }
}
</script>
<style>
/*.el-select-dropdown__item {*/
/*  padding: 0;*/
/*  width: 100%;*/
/*  height: 100%;*/
/*}*/

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
